const http = require('http');
const url = require('url');
const {getUserInfo,trade,RegistUser} = require('../Bid.js')
const {getUserOrders} = require('../all.js')
const {getMeter} = require('./fromTESP')

var reqNum = 0;
var bidNum = 0;
// 192.168.211.130
// 创建HTTP服务器
const server = http.createServer(async (req, res) => {
    if (req.method === 'GET' && req.url.startsWith('/getUserInfo')) {

        // 解析URL和查询字符串
        const parsedUrl = url.parse(req.url,true);
        const query = parsedUrl.query;
        console.log(query.UserId)
        let user = query.UserId
       // 查询订单接口
       //order = '{"id":"user3","token":180,"Inputs":100,"Outputs":0,"orders":[],"total":100}'
       result = ""
       try{
          if (user!=null){
            result = await getUserInfo(user);
          }
       }catch(error){
          result = "err"
       }
       res.statusCode = 200;
       res.setHeader('Content-Type', 'application/json');
       res.end(JSON.stringify(result));

    } else if (req.method === 'GET' && req.url.startsWith('/getOrder')) {
      // 解析URL和查询字符串
      const parsedUrl = url.parse(req.url,true);
      const query = parsedUrl.query;
      
      // 获取参数值
      const auctionId = query.auctionId;
      // 打印参数
      const result = await getUserInfo(auctionId)
   
      console.log(JSON.stringify(result))

      // 发送响应
      res.statusCode = 200;
      res.setHeader('Content-Type', 'application/json');
      res.end(JSON.stringify(result));
    } else if (req.method === 'GET' && req.url.startsWith('/queryOrders')) {
      // 解析URL和查询字符串
      const parsedUrl = url.parse(req.url,true);
      const query = parsedUrl.query;
      
      // 获取参数值
      const userId = query.userId;

      // // 打印参数
      console.log('userId : '+userId)
      const result = await getUserOrders(userId)
      console.log(JSON.stringify(result))

      // 发送响应JSON.stringify(result)
      res.statusCode = 200;
      res.setHeader('Content-Type', 'application/json');
      res.end(JSON.stringify(result));
    } else if (req.method === 'GET' && req.url.startsWith('/reqSell')) {
        // 解析URL参数
        const urlParams = new URLSearchParams(req.url.slice(1));
        
        // 获取参数值
        const userId = urlParams.get('UserId');
        const amount = parseFloat(urlParams.get('Amount'));
        const price = parseFloat(urlParams.get('Price'));
        const inputs = amount

        // 创建包含参数的对象
        const meter = {
          UserId: userId,
          Inputs: inputs,
          Outputs: 0,
          Amount: amount,
          Price: price
        };
        // 向fabric提出交易请求
        let numArr = await trade(userId,meter);
        reqNum = numArr[0];
        bidNum = numArr[1];
        // 发送响应
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/plain');
        res.end('Parameters received and logged.');
    } else if (req.method === 'GET' && req.url.startsWith('/reqBuy')) {
      // 解析URL参数
      const urlParams = new URLSearchParams(req.url.slice(1));
      
      // 获取参数值
      const userId = urlParams.get('UserId');
      const amount = parseFloat(urlParams.get('Amount'));
      const price = parseFloat(urlParams.get('Price'));
      const outputs = amount

      // 创建包含参数的对象
      const meter = {
        UserId: userId,
        Inputs: 0,
        Outputs: outputs,
        Amount: amount,
        Price: price
      };
      // 打印参数
      console.log(meter);
      let numArr = await trade(userId,meter);
      reqNum = numArr[0];
      bidNum = numArr[1];

      // 发送响应
      res.statusCode = 200;
      res.setHeader('Content-Type', 'text/plain');
      res.end('Parameters received and logged.');
    } else if (req.method === 'GET' && req.url.startsWith('/regist')) {
      
        // 解析URL和查询字符串
        const parsedUrl = url.parse(req.url,true);
        const query = parsedUrl.query;
        console.log(query.UserId)
        let user = query.UserId

        await RegistUser(user);

      // 发送响应
      res.statusCode = 200;
      res.setHeader('Content-Type', 'text/plain');
      res.end('Parameters received and logged.');
    } else if (req.method === 'GET' && req.url.startsWith('/querySysNum')) {
      let resArr = [reqNum,bidNum]
      console.log(reqNum,' ',bidNum)
      reqNum = 0;
      bidNum = 0;
      // 发送响应
      res.statusCode = 200;
      res.setHeader('Content-Type', 'text/plain');
      res.end(JSON.stringify(resArr));
  }else {
        res.statusCode = 404;
        res.end('Not found.');
    }
  });
  
  // 监听端口并启动服务器
  const port = 3001;
  server.listen(port, () => {
    console.log(`Server is running on port ${port}`);
  });